package com.nuliji.util.shiro;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.Objects;

/**
 * Created by GaoJie on 2017/11/3.
 */
public class DevelopRealm extends AuthorizingRealm {
    private static final FastDateFormat dateFormat = FastDateFormat.getInstance("yyyy-MM-dd HH:mm:ss");


    private static final Logger logger = LoggerFactory.getLogger(DevelopRealm.class);

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String className = DevelopRealm.class.getName();
        boolean selected = false;
        for(String realmNames: principalCollection.getRealmNames()){
            if(realmNames.contains(className)) selected = true;
        }
        if(!selected) return null;
        ArrayList<String> roleAuthorization = new ArrayList<String>();
        SimpleAuthorizationInfo sa = new SimpleAuthorizationInfo();
        roleAuthorization.add("develop");
        sa.addRoles(roleAuthorization);
        return sa;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        String password = new String(token.getPassword());
        logger.info("Login info: "+username+","+password);

        if (StringUtils.isBlank(username) || StringUtils.isBlank(password)) {
            throw new UnknownAccountException("用户名或密码不能为空！");
        }
        if (Objects.equals(username, "develop")
                && Objects.equals(password, "develop")) {
        }else{
            throw new IncorrectCredentialsException("用户名或密码错误！");
        }
        return new SimpleAuthenticationInfo(username, password, getName());
    }
}
